from rest_framework.permissions import IsAdminUser
from rest_framework.response import Response
from rest_framework.views import APIView
from six_it.models import Label, Question
from wgu_1220968732.serializer import LabelListSerializer, AttentionLabelListSerializer, \
    WaitAnswerQuestionsSerializer, LatestAnswerQuestionsSerializer, HotAnswerQuestionsSerializer


class LabelListView(APIView):
    '''标签列表'''

    def get(self, request):
        '''获取所有标签列表'''
        labels = Label.objects.all()
        serializer = LabelListSerializer(labels, many=True)

        return Response(serializer.data)


class AttentionLabelListView(APIView):
    '''获取用户关注的标签'''

    def get(self, request):

        labels = Label.objects.filter(users=request.user.id)
        serializer = AttentionLabelListSerializer(labels, many=True)

        return Response(serializer.data)


class LatestAnswerQuestionsView(APIView):
    '''获取最新被回答过的问题列表'''

    def get(self, request, id):

        if id == "-1":
            questions = Question.objects.all().order_by("-replytime")
        else:
            label = Label.objects.get(id=id)
            questions = label.questions.all().order_by("-replytime")
        serializer = LatestAnswerQuestionsSerializer(instance=questions, many=True)

        return Response(serializer.data)


class HotAnswerQuestionsView(APIView):
    '''获取回答数较多的问题列表'''

    def get(self, request, id):

        if id == '-1':
            questions = Question.objects.all().order_by('visits')
        else:
            label = Label.objects.get(id=id)
            questions = label.questions.all().order_by('visits')
        serializer = HotAnswerQuestionsSerializer(instance=questions, many=True)

        return Response(serializer.data)


class WaitAnswerQuestionsView(APIView):
    '''获取还未被回答的问题列表'''

    def get(self, request, id):
        if id == '-1':
            questions = Question.objects.filter(reply=0).order_by("-updatetime")
        else:
            label = Label.objects.get(id=id)
            questions = label.questions.filter(reply=0).order_by("-updatetime")
        serializer = WaitAnswerQuestionsSerializer(instance=questions, many=True)

        return Response(serializer.data)


class TechnologyView(APIView):
    '''擅长技术'''
    def put(self,request):
        user = request.user
        labels=request.data.get('labels')
        user.labels.remove(*user.labels.all())
        for label_id in labels:
            label = Label.objects.get(id=label_id)
            label.users.add(user)
        return Response({"errmsg":"OK"})


